<template>
    <div>
        <el-row>
            <el-col :span="24">
                <div>
                    <el-button type="primary" @click="addBtn">上报</el-button>
                    <el-button type="danger" plain @click="deleteAllBtn">批量删除</el-button>

                    <!-- 隐藏输入框 -->
                    <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" />

                    <!-- 点击触发文件选择的导入按钮 -->
                    <el-button plain @click="triggerFileSelect">导入</el-button>

                    <el-button plain @click="exportExcel">导出</el-button>

                    <el-button plain @click="TryPrintf">打印</el-button>
                </div>
            </el-col>
        </el-row>
        <br>
        <el-row>
            <el-col :span="24">
                <el-form :inline="true" :model="param">

                    <el-form-item label="处理状态">
                        <el-select v-model="param.processingStatus" placeholder="请选择">
                            <el-option label="待处理" value="1"></el-option>
                            <el-option label="已完成" value="2"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="订单状态">
                        <el-select v-model="param.orderStatus" placeholder="请选择">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="待审核" value="0"></el-option>
                            <el-option label="待接单" value="1"></el-option>
                            <el-option label="待提单" value="2"></el-option>
                            <el-option label="待发车" value="3"></el-option>
                            <el-option label="运输中" value="4"></el-option>
                            <el-option label="代签收" value="5"></el-option>
                            <el-option label="已完成" value="6"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="事件日期">
                        <el-date-picker type="daterange" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" v-model="param.happenTime">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="处理日期">
                        <el-date-picker type="daterange" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" v-model="param.handleTime">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="" label-width="100px">
                        <el-input placeholder="请输入关键词搜索" style="width: 200px; margin-left: 10px;"
                            v-model="param.departmentName">
                        </el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="queryAll">查询</el-button>
                        <el-button style="margin-left: 10px;" @click="clearSearch">重置</el-button>
                    </el-form-item>

                </el-form>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24">
                <div>
                    <el-table :data="tableData" style="width: 100%; margin-top: 20px;"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55">
                        </el-table-column>
                        <el-table-column prop="id" label="异常单号" width="200"></el-table-column>

                        <!-- 客户/用户列 -->
                        <el-table-column label="客户/用户" width="120">
                            <template slot-scope="scope">
                                <!-- 根据是否有客户名称或用户名称动态显示 -->
                                <span>{{ scope.row.customerId || scope.row.userId }}</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="orderStatus" label="订单状态" width="80">
                            <template slot-scope="scope">
                                <span v-if="scope.row.orderStatus == 0" style="color: red;">待审核</span>
                                <span v-else-if="scope.row.orderStatus == 1" style="color: #00FF00;">待接单</span>
                                <span v-else-if="scope.row.orderStatus == 2" style="color: #00FF00;">待提单</span>
                                <span v-else-if="scope.row.orderStatus == 3" style="color: #00FF00;">待发车</span>
                                <span v-else-if="scope.row.orderStatus == 4" style="color: #00FF00;">运输中</span>
                                <span v-else-if="scope.row.orderStatus == 5" style="color: #00FF00;">代签收</span>
                                <span v-else-if="scope.row.orderStatus == 6" style="color: #00FF00;">已完成</span>
                                <span v-else style="color: gray;">未知</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="companyName" label="承运商" width="100"></el-table-column>
                        <el-table-column prop="driverName" label="司机" width="100"></el-table-column>
                        <el-table-column prop="tel" label="联系方式" width="150"></el-table-column>
                        <el-table-column prop="carNum" label="车牌号" width="100"></el-table-column>

                        <el-table-column prop="eventType" label="事件类型" width="100">
                            <template slot-scope="scope">
                                <span v-if="scope.row.eventType == 0">交通事故</span>
                                <span v-else-if="scope.row.eventType == 1">车辆事故</span>
                                <span v-else-if="scope.row.eventType == 2">货物破损</span>
                                <span v-else-if="scope.row.eventType == 3">地址错误</span>
                                <span v-else-if="scope.row.eventType == 4">收件人拒收</span>
                                <span v-else>丢失包裹</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="eventTime" label="事件时间" width="100"></el-table-column>
                        <el-table-column prop="eventLocation" label="事件地点" width="100"></el-table-column>
                        <el-table-column prop="eventDescription" label="事件说明" width="150"></el-table-column>

                        <el-table-column label="事件照片" width="150">
                            <template v-slot="scope">
                                <img v-if="scope.row.images" :src="scope.row.images" class="avatar-img" height="50px" />
                                <div v-else class="avatar-placeholder">
                                    <i class="el-icon-picture"></i>
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="usersName" label="上报人" width="100"></el-table-column>
                        <el-table-column prop="reportTime" label="上报时间" width="100"></el-table-column>

                        <el-table-column prop="processingStatus" label="处理状态" width="100">
                            <template slot-scope="scope">
                                <span v-if="scope.row.processingStatus == 2" style="color: red;">已完成</span>
                                <span v-else style="color: gray;">待处理</span>
                            </template>
                        </el-table-column>

                        <el-table-column prop="poweruserId" label="处理人" width="100"></el-table-column>
                        <el-table-column prop="processingTime" label="处理时间" width="100"></el-table-column>
                        <el-table-column prop="processingMeasures" label="处理措施" width="150"></el-table-column>
                        <el-table-column label="操作" width="200">
                            <template slot-scope="scope">
                                <el-button type="text" size="medium" @click="updateBtn(scope.row)">编辑</el-button>
                                <el-button type="text" size="medium" @click="switchBtn(scope.row.id)">处理异常</el-button>
                                <el-button v-if="hasPermission('finish')" type="text" size="medium"
                                    @click="finish(scope.row.id)">完成</el-button>
                                <el-button type="text" size="medium" style="color: red;"
                                    @click="deleteBtn(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-col>
        </el-row>


        <el-row>
            <el-col :span="24">
                <!-- 分页部分 -->
                <div>
                    <el-pagination background :page-sizes="[5, 10, 20, 50]" :page-size="pageSize"
                        :current-page="pageNum" layout="total, sizes, prev, pager, next, jumper" :total="total"
                        @prev-click="prePage" @next-click="nextPage" @current-change="curPage"
                        @size-change="sizeChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>




        <!-- 添加弹窗 -->
        <el-dialog title="异常上报" :visible.sync="addVisible">
            <el-form>
                <el-form-item label="事件类型" label-width="80px">
                    <el-select placeholder="请选择" style="width: 120px;" v-model="add.eventType">
                        <el-option label="交通事故" value="0"></el-option>
                        <el-option label="车辆事故" value="1"></el-option>
                        <el-option label="货物破损" value="2"></el-option>
                        <el-option label="地址错误" value="3"></el-option>
                        <el-option label="收件人拒收" value="4"></el-option>
                        <el-option label="丢失包裹" value="5"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="运单号" label-width="80px">
                    <el-input v-model="add.waybillId"></el-input>
                </el-form-item>

                <el-form-item label="事件日期">
                    <el-date-picker v-model="add.eventTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="事件地点" label-width="80px">
                    <el-input v-model="add.eventLocation"></el-input>
                </el-form-item>

                <el-form-item label="事件说明" label-width="80px">
                    <el-input v-model="add.eventDescription"></el-input>
                </el-form-item>

                <el-form-item label="异常照片">
                    <el-upload class="avatar-uploader" action="api/exception/imgLoad" :on-success="handleAvatarSuccess"
                        :show-file-list="false" :headers="customHeaders">
                        <img v-if="add.images" :src="add.images" class="avatar-img" />
                        <div v-else class="avatar-placeholder">
                            <i class="el-icon-plus avatar-icon"></i>
                        </div>
                    </el-upload>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </div>
        </el-dialog>


        <!-- 修改弹窗 -->
        <el-dialog title="上报修改" :visible.sync="updateVisible">
            <el-form>
                <el-form-item label="事件类型" label-width="80px">
                    <el-select placeholder="请选择" style="width: 120px;" v-model="add.eventType">
                        <el-option label="交通事故" value="0"></el-option>
                        <el-option label="车辆事故" value="1"></el-option>
                        <el-option label="货物破损" value="2"></el-option>
                        <el-option label="地址错误" value="3"></el-option>
                        <el-option label="收件人拒收" value="4"></el-option>
                        <el-option label="丢失包裹" value="5"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="运单号" label-width="80px">
                    <el-input v-model="add.waybillId"></el-input>
                </el-form-item>

                <el-form-item label="事件日期">
                    <el-date-picker v-model="add.eventTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="事件地点" label-width="80px">
                    <el-input v-model="add.eventLocation"></el-input>
                </el-form-item>


                <el-form-item label="事件说明" label-width="80px">
                    <el-input v-model="add.eventDescription"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="updateVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveUpdate">确 定</el-button>
            </div>
        </el-dialog>






    </div>
</template>

<script>
export default {
    data() {
        return {
            pageSize: 10,
            pageNum: 1,
            total: 0,

            tableData: [],//表格对象
            param: {},//查询参数对象
            params: {},//finish方法专用
            addVisible: false,
            updateVisible: false,
            add: {},
            multipleSelection: [],
            token: '', // 初始化 token
            customHeaders: {},

            userPermissions: [] // 用于保存用户权限
        }
    },

    methods: {
        // 获取用户权限
        fetchUserPermissions(userIds) {
            this.$axios.get('api/menu/permissions/' + userIds)
                .then(response => {
                    if (response.data.code === 200) {
                        this.userPermissions = response.data.data; // 保存用户权限
                    }
                })
                .catch(error => {
                    console.error("获取用户权限失败:", error);
                });
        },
        // 检查用户是否有某个权限
        hasPermission(authCode) {
            return this.userPermissions.includes(authCode);
        },



        // ------------------------------------------------------------------



        queryAll() {
            let pageParam = {};
            pageParam.pageNum = this.pageNum;
            pageParam.pageSize = this.pageSize;
            pageParam.param = this.param;
            this.$axios.post('api/exception/queryException', pageParam)
                .then(resp => {
                    console.log(resp.data);
                    if (resp.data.code == 200) {
                        this.tableData = resp.data.data.list;
                        this.total = resp.data.data.total;
                    }

                })
        },
        //打开弹窗
        addBtn() {
            this.$axios.post('api/exception/addIdByImg', this.add)
                .then(response => {
                    if (response.data.code == 200) {
                        console.log(response);

                        this.add.id = response.data.data;
                        this.addVisible = true;
                    }
                })
        },

        saveAdd() {
            this.$axios.post('api/exception/add', this.add)
                .then(response => {
                    if (response.data.code == 200) {
                        this.addVisible = false;
                        this.open1();
                        this.queryAll();
                        this.$message({
                            message: '上报成功',
                            type: 'success'
                        });
                    }
                })
        },
        open1() {
            this.$notify({
                title: '新消息',
                message: '警告：新异常！',
                type: 'warning'
            });
        },
        saveUpdate() {
            this.$axios.post('api/exception/update', this.add)
                .then(response => {
                    if (response.data.code == 200) {
                        this.updateVisible = false;
                        this.queryAll();
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                    }
                })
        },
        clearSearch() {
            this.param = {};
            this.queryAll();
        },
        finish(id) {
            this.$axios.get('api/exception/queryById/' + id)
                .then(response => {
                    if (response.data.code === 200) {
                        this.params = response.data.data;
                        return this.$axios.post('api/exception/updateByFinish', this.params);
                    } else {
                        throw new Error('查询异常失败');
                    }
                })
                .then(response => {
                    if (response.data.code === 200) {
                        this.queryAll(); // 更新数据
                        this.$message({
                            message: '处理成功',
                            type: 'success'
                        });
                    } else if (response.data.code == 500) {
                        alert('不能重复处理或不存在处理措施');
                    }
                })
        },
        updateBtn(value) {
            this.updateVisible = true;
            this.$axios.get('api/exception/queryById/' + value.id)
                .then(response => {
                    if (response.data.code == 200) {
                        this.add = response.data.data;//数据回显
                    } else {
                        alert("数据回显错误,检查前端代码");
                    }
                })
        },
        deleteBtn(id) {
            this.$confirm('此操作将永久删除该内容, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get(`api/exception/delete/` + id)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.queryAll();
                        } else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            });
                        }
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        /**
         * 批量删除
         */
        deleteAllBtn() {
            // 确保用户至少选中了一项
            if (this.multipleSelection.length === 0) {
                this.$message({
                    type: 'warning',
                    message: '请选择要删除的项!'
                });
                return;
            }

            // 提取选中的 id
            let ids = this.multipleSelection.map(item => item.id);

            // 弹出确认框
            this.$confirm('此操作将永久删除选中的内容, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 执行删除请求
                this.$axios.post('api/exception/batchDelete', ids)
                    .then(response => {
                        if (response.data.code == 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.queryAll(); // 刷新数据
                            this.multipleSelection = []; // 清空选中的项
                        } else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            });
                        }
                    })
                    .catch(error => {
                        this.$message({
                            type: 'error',
                            message: '删除请求失败!'
                        });
                    });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleSelectionChange(val) {
            //点击复选框的事件val：是选中的对象数组
            console.log(val)
            this.multipleSelection = val;
        },
        switchBtn(id) {
            localStorage.setItem("idInfo", JSON.stringify(id));
            this.$router.push({ path: '/ko' });
        },


        /**
         * 导出
         */
        exportExcel() {

            // 使用 axios 获取文件流
            this.$axios({
                url: 'api/exception/export',
                method: 'GET',
                responseType: 'blob',  // 指定响应类型为 blob
            }).then(response => {
                // 创建 Blob 对象
                const blob = response.data;

                // 创建一个 URL 对象来表示该 Blob
                const url = window.URL.createObjectURL(blob);

                // 创建一个临时的下载链接
                const link = document.createElement('a');
                link.href = url;
                link.download = 'data.xlsx';  // 设置下载的文件名

                // 触发点击事件下载文件
                document.body.appendChild(link);
                link.click();

                // 下载后清理链接
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url); // 释放 Blob URL
            }).catch(error => {
                console.error('导出失败:', error);
            });
        },



        /**
         * 导入功能
         */

        // 点击按钮时，触发文件选择
        triggerFileSelect() {
            this.$refs.fileInput.click();
        },
        // 处理文件选择后的导入逻辑
        handleFileChange(event) {
            const file = event.target.files[0]; // 获取用户选择的文件

            if (file) {
                // 构建 FormData 对象，准备上传文件
                const formData = new FormData();
                formData.append("file", file);

                // 发起文件上传请求
                this.uploadFile(formData);
            }
        },
        // 上传文件到后端接口
        uploadFile(formData) {
            this.$axios.post("api/exception/importData", formData, {
                headers: {
                    "Content-Type": "multipart/form-data"
                }
            })
                .then(response => {
                    // 处理成功返回的数据
                    console.log("文件导入成功", response.data);
                    alert("导入成功");
                })
                .catch(error => {
                    // 错误处理
                    console.error("文件导入失败", error);
                    alert("导入失败");
                });
        },
        TryPrintf() {
            window.print();  // 调用浏览器打印功能
        },


        /**
         * 图片上传方法
         */
        handleAvatarSuccess(response) {
            console.log(response);
            if (response.code === 200) {
                this.add.images = response.data; // 上传成功后的图片路径
                this.updateUserImg();
            } else {
                this.$message.error('上传失败');
            }
        },

        updateUserImg() {
            this.$axios.post('api/exception/updateImg', this.add)
                .then((response) => {
                    if (response.data.code === 200) {
                        this.$message.success('添加成功');
                    } else {
                        this.$message.error('添加失败');
                    }
                })
                .catch(() => {
                    this.$message.error('请求错误');
                });
        },






        // 点击上一页
        prePage() {
            if (this.pageNum > 1) {
                this.pageNum--;
                this.queryAll(); // 更新数据
            }
        },

        // 点击下一页
        nextPage() {
            if (this.pageNum < Math.ceil(this.total / this.pageSize)) {
                this.pageNum++;
                this.queryAll(); // 更新数据
            }
        },

        // 页码变化
        curPage(pageNum) {
            this.pageNum = pageNum;
            this.queryAll(); // 更新数据
        },

        // 每页显示条数变化
        sizeChange(pageSize) {
            this.pageSize = pageSize;
            this.pageNum = 1; // 每页条数变化时，回到第一页
            this.queryAll(); // 更新数据
        },



    },
    created() {

        this.token = localStorage.getItem('authorization'); // 从本地存储中获取 JWT 令牌    
        this.customHeaders = { "authorization": this.token }

        let userInfoString = localStorage.getItem('userInfo');
        let userInfo = JSON.parse(userInfoString);
        let userIds = userInfo.id;


        this.queryAll();
        this.fetchUserPermissions(userIds);
    },

}
</script>

<style scoped></style>